<template>
  <ProTable
    ref="tableRef"
    :fetchListApi="fetchList"
    :columns="columns"
    :row-selection="rowSelection"
    row-key="dictCode"
  >
    <template #toolbars>
      <Space>
        <b-button icon="add" @click="onAdd">新增</b-button>
        <b-button
          icon="delete"
          @click="() => onDelete()"
          :disabled="!selectKeys?.length"
          >删除</b-button
        >
        <b-button icon="export" @click="() => onExport()">导出</b-button>
      </Space>
    </template>
    <template #bodyCell="{ column, record }">
      <template v-if="column.dataIndex === 'operation' && !record.admin">
        <b-button icon="detail" type="link" @click="() => onView(record)"
          >详情</b-button
        >
        <b-button
          icon="del"
          type="link"
          @click="() => onDelete(record.dictCode)"
          >删除</b-button
        >
      </template>
    </template>
  </ProTable>
  <FormModal :items="items"> </FormModal>
</template>

<script setup lang="tsx">
import { computed, ref } from 'vue';
import { Modal, Space, Tag } from 'ant-design-vue';
import dayjs from 'dayjs';
import { useRoute } from 'vue-router';
import { ProFormProps } from '@/components/ProForm';
import { ProTable, ProTableProps } from '@/components/ProTable/index';
import { useFormModal } from '@/hooks/formModal';
import { download, listToEnum, listToOption } from '@/utils/utils';
import {
  createDictDetail,
  deleteDictDetail,
  exportDictDetail,
  fetchDictDetail,
  fetchDictSelect,
  fetchSysNormalDisable,
  updateDictDetail,
} from '@/api/system';
import { listClassOptions } from './constant';

const route = useRoute();

const dictType = ref(route.query.dictType);
const searchParams = ref({});

const fetchList = (params: any) => {
  dictType.value = params.dictType || route.query.dictType;

  searchParams.value = {
    ...params,
    dictType: params.dictType || route.query.dictType,
  };

  return fetchDictDetail(searchParams.value);
};

const tableRef = ref();

const dictTypes = ref<Record<string, any>>([]);

const sysNormalDisableOptions = ref<Global.Option[]>([]);
const sysNormalDisableEnum = ref<Record<string, any>>([]);

const init = () => {
  fetchSysNormalDisable().then((res) => {
    sysNormalDisableOptions.value = listToOption(
      res.data,
      'dictLabel',
      'dictValue',
    ) as Global.Option[];
    sysNormalDisableEnum.value = listToEnum(res.data, 'dictValue', 'dictLabel');
  });
  fetchDictSelect().then((res) => {
    dictTypes.value = listToEnum(res.data as any[], 'dictType', 'dictName');
  });
};

init();

const selectKeys = ref<number[]>([]);
const rowSelection = computed<ProTableProps['rowSelection']>(() => {
  return {
    selectedRowKeys: selectKeys.value,
    onChange(values, all) {
      selectKeys.value = values as number[];
    },
  };
});

const columns = computed<ProTableProps['columns']>(() => [
  {
    title: '字典名称',
    dataIndex: 'dictType',
    hideInTable: true,
    defaultValue: route.query.dictType,
    valueEnum: {
      ...dictTypes.value,
    },
  },
  {
    title: '字典编码',
    dataIndex: 'dictCode',
    hideInSearch: true,
  },
  {
    title: '字典标签',
    dataIndex: 'dictLabel',
  },
  {
    title: '字典键值',
    dataIndex: 'dictValue',
    hideInSearch: true,
  },
  {
    title: '字典排序',
    dataIndex: 'dictSort',
    hideInSearch: true,
  },
  {
    title: '状态',
    dataIndex: 'status',
    valueEnum: {
      ...sysNormalDisableEnum.value,
    },
    customRender({ text }) {
      return (
        <Tag color={text === '1' ? 'error' : 'processing'}>
          {sysNormalDisableEnum.value[text]}
        </Tag>
      );
    },
  },
  {
    title: '备注',
    dataIndex: 'remark',
    hideInSearch: true,
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    hideInSearch: true,
  },
  {
    title: '操作',
    dataIndex: 'operation',
    hideInSearch: true,
    fixed: 'right',
    width: 120,
  },
]);

const items = computed<ProFormProps['items']>(() => [
  {
    label: '字典类型',
    type: 'input',
    field: 'dictType',
    props: {
      disabled: true,
    },
  },
  {
    label: '数据标签',
    type: 'input',
    field: 'dictLabel',
    rules: [{ required: true, message: '请输入数据标签', trigger: 'blur' }],
    props: {
      placeholder: '请输入数据标签',
    },
  },
  {
    label: '数据键值',
    type: 'input',
    field: 'dictValue',
    rules: [{ required: true, message: '请输入数据键值', trigger: 'blur' }],
    props: {
      placeholder: '请输入数据键值',
    },
  },
  {
    label: '样式属性',
    type: 'input',
    field: 'cssClass',
    props: {
      placeholder: '请输入样式属性',
    },
  },
  {
    label: '显示排序',
    type: 'number',
    rules: [{ required: true, message: '请输入显示排序', trigger: 'blur' }],
    field: 'dictSort',
    props: {
      placeholder: '请输入显示排序',
    },
  },
  {
    label: '回显样式',
    type: 'select',
    field: 'listClass',
    props: {
      options: listClassOptions,
      placeholder: '请选择回显样式',
    },
  },
  {
    label: '状态',
    type: 'radio',
    field: 'status',
    props: {
      options: sysNormalDisableOptions.value,
    },
  },
  {
    label: '备注',
    type: 'textarea',
    field: 'remark',
    props: {
      placeholder: '请输入备注',
      showCount: true,
      maxlength: 200,
    },
  },
]);

const { FormModal, open } = useFormModal({ size: 'small' });

const onAdd = async () => {
  open({
    title: '新增',
    defaultValue: {
      dictType: dictType.value,
      status: '0',
    },
    serviceApi: async (params: any): Promise<any> => {
      await createDictDetail(params);
      tableRef.value.refresh();
    },
  });
};

const onView = async (record: any) => {
  open({
    title: (type) => (type === 'info' ? '详情' : '编辑'),
    modalType: 'info',
    defaultValue: {
      ...record,
    },
    serviceApi: async (params: any): Promise<any> => {
      await updateDictDetail({
        ...params,
      });
      tableRef.value.refresh();
    },
  });
};

const sleep = (cb) => {
  setTimeout(() => {
    cb();
  }, 500);
};

const onDelete = async (id?: string) => {
  const ids = id ? [id] : selectKeys.value;
  Modal.confirm({
    title: '系统提示',
    content: `确认要删除当前选项？`,
    onOk: async () => {
      await deleteDictDetail(ids);
      sleep(() => tableRef.value.refresh());
      selectKeys.value = [];
    },
  });
};

const onExport = async () => {
  const res = await exportDictDetail(searchParams.value);
  download(
    res as unknown as Blob,
    `data_${dayjs().format('YYYY-MM-DD HH:mm:ss')}.xlsx`,
  );
};
</script>
